package com.see.client;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.table.TableModel;

import com.see.client.exception.BadOrderException;
import com.see.domain.Order;
import com.see.domain.Protocol;
import com.see.exception.MessegeFeedException;
import com.see.exception.UserExistException;

public class TradingClientImpl implements TradingClient {
	private String userName;
	private boolean isLogin = false; 
	private ClientSocketConnection clientsoket;

	
	@Override
	public void connect(String userName, String serverAdress, int port, Listener listner)
			throws UserExistException, UnknownHostException, IOException, MessegeFeedException {
		
		if(userName == null || userName.equals(""))
			throw new MessegeFeedException(Protocol.ERROR_USERNAME);
		
		this.userName = userName;
		
		if(port == 0 || port < 1037)
			throw new MessegeFeedException(Protocol.ERROR_PORT);
		
		if(serverAdress == null || serverAdress.equals(""))
			throw new MessegeFeedException(Protocol.ERROR_SERVADRESS);
		
		clientsoket = new ClientSocketConnection(new Socket(serverAdress, port), listner, this);
		clientsoket.run();
		
		clientsoket.login();
		isLogin = true;
	}

	@Override
	public int sendOrder(Order order) throws BadOrderException, MessegeFeedException {
		return clientsoket.sendOrder(order);
	}

	@Override
	public void close() {
		this.isLogin = false;
		clientsoket.close();
	}

	@Override
	public void addLisner(Listener listener) {
		if (listener == null) {
			throw new IllegalArgumentException(
					"listener null value");
		}
		clientsoket.addLisner(listener);
	}

	@Override
	public void removeLisner(Listener listener) {
		if (listener == null) {
			throw new IllegalArgumentException(
					"listener null value");
		}
		clientsoket.removeLisner(listener);
	}
	
	

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public boolean isLogin() {
		return isLogin;
	}

	public void setLogin(boolean isLogin) {
		this.isLogin = isLogin;
	}
	
	

}
